package com.qf.controller;

import com.qf.pojo.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Description: 公用常量
 * @Data: 2022/9/13 16:15
 * @Pacakge: com.qf.controller
 * @ClassName: UserController
 * @Author: fan
 * 控制层
 */
@Controller
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;
    @RequestMapping("findAll")
    public ModelAndView findAll(){
        ModelAndView modelAndView = new ModelAndView();
        List<User> list = userService.findAll();
        modelAndView.setViewName("user");
        modelAndView.addObject("users", list);
        return modelAndView;
    }
    @RequestMapping("login")
    public String findUserByUsername(User user, HttpSession httpSession) {
        Boolean login = userService.findUserByUsername(user,httpSession);
        if (login) {
            return "redirect:/user/findAll";
        } else {
            return "index";
        }
    }
    @RequestMapping("findUserById")
    public ModelAndView findUserById(Integer id){
        ModelAndView modelAndView = new ModelAndView();
        User user = userService.findUserById(id);
        modelAndView.addObject("user",user);
        modelAndView.setViewName("update");
        return modelAndView;
    }
    @RequestMapping("updateUser")
    public String updateUser(User user){
        //判断user的id是不是为空,为空是新增,不为空时是修改
        if (user.getId() == null){
            userService.insertUser(user);
        }else{
            userService.updateUser(user);
        }
        return "redirect:/user/findAll";
    }
    @RequestMapping("deleteUserById")
    public String deleteUserById(Integer id){
        userService.deleteUserById(id);
        return "redirect:/user/findAll";
    }
    @RequestMapping("insertUser")
    public String insertUser(){
        return "insert";
    }
}
